package com.caiyouxi.msg.service.impl;

import com.caiyouxi.common.bean.QueryParams;
import com.caiyouxi.common.bean.ResData;
import com.caiyouxi.common.cache.RedisService;
import com.caiyouxi.common.service.BaseService;
import com.caiyouxi.msg.mapper.MessagesMapper;
import com.caiyouxi.msg.model.Messages;
import com.caiyouxi.msg.service.MessagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class MessagesServiceImpl extends BaseService implements MessagesService {
    @Autowired
    private MessagesMapper mapper;
    @Autowired
    private RedisService redisService;

    @Override
    public ResData delete_messages(Messages bean) {
        return success(mapper.delete_messages(bean.getId()));
    }

    @Override
    public ResData insert_message(Messages bean) {
        if(bean.getCreatedTime() == null){
            bean.setCreatedTime(new Date());
        }
        return success(mapper.insert_message(bean));
    }

    @Override
    public ResData select_single_message(Messages bean) {
        ResData data = success(mapper.select_single_message(bean.getId()));
        //设置当前用户的阅读时间
        if(data.getData() != null){
            bean.setProductCode(null);
            bean.setSourceId(null);
            bean.setSourceObjectId(null);
            bean.setSourceObjectType(null);
            bean.setReceiverId(null);
            bean.setCreatedTime(null);
            bean.setNotifyTime(null);
            bean.setExpireTime(null);
            bean.setTitle(null);
            bean.setStatus(null);
            bean.setExtraData(null);
            bean.setContent(null);
            bean.setIs_del(null);
            bean.setReadedTime(new Date());
            mapper.update_messagee(bean);
        }
        return data;
    }

    @Override
    public ResData update_messagee(Messages record) {
        return success(mapper.update_messagee(record));
    }

    @Override
    public ResData get_all_message(Messages bean) {
        Integer pageSize = Integer.parseInt(redisService.get("sys.pagesize").toString());//后台获取默认每页多少调数据
        QueryParams pageList = new QueryParams();

        Integer p = bean.getPage_size();                            //查看前台是否给了每页几条数据
        if(p == 0 || p == null){
            p = pageSize;                                           //如果没给数据，则取默认数据
        }
        bean.setPage_size(p);
        pageList.setPage(bean.getPage());
        pageList.setTotal(mapper.get_count_message(bean));
        pageList.setList(mapper.get_all_message(bean));
        pageList.setPage(bean.getPage());
        return success(pageList);
    }
}
